
var _bank = [];

$(function() {
	$.extend({
		format: function(str, step, splitor) {
			str = str.toString();
			var len = str.length;

			if (len > step) {
				var i = 0, s = "", arr = [];
				while (i < len) {
					s = str.substr(i, step);					
					arr.push(s);					
					i += step;					
				}				 
				 
				str = arr.join(splitor);
			 }
			
			 return str;
		}
	});
});

var Pay = {
	collapse: function (cc) {
		var a = $('#payment').val();
		if (a == '2') {
			$("#label_payment_bank").toggle();
			
			if ($(cc).hasClass("ui-icon-circle-triangle-w")) {
				$(cc).removeClass("ui-icon-circle-triangle-w").addClass("ui-icon-circle-triangle-s");			
			} else {
				$(cc).removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-w");
			}
		}
		
		return false;
	},
	
	emp: function (a) {
		var body = {};
		body.q = a;
		
		$.getJSON('finance.php?do=PaymentMy.ajax_bank1', body, function(json) {
			_bank = json;
			
			Pay.payment($('#payment').val());
		});
	},
	
	payment: function (a) {
		if (a == '2' || a == '4') {
			return this.payment_x();
		}
		
		$("#label_payment_bank").hide();
		$("#payment_x").removeClass("ui-icon-circle-triangle-s").addClass("ui-icon-circle-triangle-w");
		
		return false;
	},
	
	payment_x: function () {
		$select = $("#payment_bank");		
		$select.empty();
		
		var count = 0;
		$.each(_bank, function(k, v) {
			var a;
			if (v.id == '-') {
				a = v.name;
			} else {
				var s = v.code.replace(/\s+/g, "");
				a = v.name + " [" + v.bank + ", " + s.right(4) + "]";				
			}
			// alert($.toJSON(v));
			
	    	var item = new Option(a, v.id);
	    	$select[0].options.add(item);
	    	/*
	    	if (count == 1) {
	    		Pay.payment_bank(v.id, false);
	    	}*/
	    	
	    	count++;
	    });
		
		$select.change(function() {
			var id = $(this).val();
			Pay.payment_bank(id, true);
		});
		
		$("#label_payment_bank").show();
		$("#payment_x").removeClass("ui-icon-circle-triangle-w").addClass("ui-icon-circle-triangle-s");
		
		var code = $("input[id^='x_code']:visible").val();
		var b = $.format(code.replace(/\s/g, ''), 4, ' ');
		$("#code_t").html(b);
		
		$("input[id^='x_code']:visible").keyup(function() {
			var s = $(this).val();
			// alert(s);
			var a = s.replace(/\s/g, '');
			
			var b = $.format(a, 4, ' ');
			//$(this).val(b);
			$("#code_t").html(b);
		});
	},
	
	payment_bank: function (id, select) {
		var url = 'finance.php?do=Bank.ajax_id&q=' + id;
		$.getJSON(url, function(json) {
			var aaa = Pay.aaa();
			if (select || aaa) {
				$("#x_bank").val(json.bank + json.branch);
				$("#x_name").val(json.name);
				$("#x_code").val(json.code);
			}
		});
	},
	
	aaa: function() {
		if ($("#x_bank").val().trim() != "") {
			return false;
		}
		 
		if ($("#x_name").val().trim() != "") {
			return false;
		} 
		
		if ($("#x_code").val().trim() != "") {
			return false;
		}
		
		return true;
	}
};
